package com.yang.webapi.auth.handler;


import com.yang.security.model.LoginUser;
import com.yang.security.token.TokenHelper;
import com.yang.security.token.TokenService;
import com.yang.security.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by baipan
 * Date: 2019/12/19
 * 用户拦截AOP
 */
@Slf4j
@Aspect
@Component
public class UserInfoHandler {

    @Autowired
    private TokenService tokenService;


    @Before("execution(* com.yang..*.controller..*.*(..))")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        if (StringUtils.startsWith(request.getRequestURI(), "/login")) {
            return;
        }

        String token = TokenHelper.getToken(request);
        if (StringUtils.isNotBlank(token)) {
            LoginUser loginUser = tokenService.getLoginUser(token);

            //设置UserUtils值
            UserUtils.setUserId(loginUser.getId());
            UserUtils.setUser(loginUser);
        }
    }


    @After("execution(* com.yang..*.controller..*.*(..))")
    public void after() {
        //清除User ThreadLocal
        UserUtils.clear();
    }



}
